package com.dyh.quickdemo.demos.threBank;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/*
@Author=Joey Wheeler
@Date=2020/10/30 16:31
*/
public class LoanSemaphore {

    private int maxLoan;
    private final AtomicInteger count = new AtomicInteger(0);
    private final AtomicBoolean canLoan = new AtomicBoolean(true);

    public LoanSemaphore(int maxLoan){
        this.maxLoan = maxLoan;
    }

    public boolean tryAcquire() {
        int currentCount = count.incrementAndGet();
        if (currentCount > maxLoan) {
            count.decrementAndGet();
            canLoan.set(false);
            return false;//借款失败 不能直接if currentCount>maxLoan 要利用AtomicInteger 卡一下
        } else {
            return true;
        }
    }


    public void release() {
        count.decrementAndGet();
    }


    public int loanInUsed() {
        return count.get();
    }


    public static void main(String[] args) {
        LoanSemaphore loanSemaphore = new LoanSemaphore(2);

        System.out.println("第一次借钱======");
        System.out.println(loanSemaphore.loanInUsed());
        System.out.println(loanSemaphore.tryAcquire());
        System.out.println(loanSemaphore.loanInUsed());

        System.out.println("第二次借钱======");
        System.out.println(loanSemaphore.loanInUsed());
        System.out.println(loanSemaphore.tryAcquire());
        System.out.println(loanSemaphore.loanInUsed());

        System.out.println("第三次借钱======");
        System.out.println(loanSemaphore.loanInUsed());
        System.out.println(loanSemaphore.tryAcquire());
        System.out.println(loanSemaphore.loanInUsed());
    }

}
